package com.zhu.ttwords.presenter;

import android.content.Context;
import android.util.Log;

import com.zhu.ttwords.TTWORDS;
import com.zhu.ttwords.bean.UserBean;
import com.zhu.ttwords.common.DBTool;
import com.zhu.ttwords.view.activity.ILoginActivity;

import java.lang.reflect.InvocationTargetException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by KnightYe on 2015/4/4.
 * 登录业务逻辑处理器
 */
public class LoginPresenter {
    ILoginActivity activity;
    Context context;

    public LoginPresenter(Context context, ILoginActivity activity) {
        this.activity = activity;
        this.context = context;
    }

    public void loginAction(String username, String password) {
        //TODO 验证登录信息
        UserBean bean = null;
        String[] param = new String[2];
        param[0] = username;
        param[1] = username;
        try {
            bean = (UserBean) DBTool.getSingleBean(UserBean.class, TTWORDS.SQL_LOGIN_CHECK, param);
        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            e.printStackTrace();
        }
        if (bean != null && bean.getPassword().equals(password)) {
            TTWORDS.getAppSetting().setUserId(bean.getUid());
            activity.loginResult(TTWORDS.TRANS_SUCCESS);
        } else {
            activity.loginResult(TTWORDS.TRANS_SERVER_WRONG);
        }
    }

    public void register() {
        activity.gotoRegister();
    }

    public void forgetPassword() {

    }

    /**
     * 加载数据库,初始化。
     */
    public void init() {
        checkDataBase();
        activity.loadComplate();
    }

    /**
     * 数据库检查
     */
    private void checkDataBase() {
        // 判断数据库目录存在
        DBTool.initDatabaseDir(context);
        // 判断数据库文件存在
        DBTool.initDatabaseFile(context);
        // 判断数据库版本
        Log.d("LoginPresenter", "SP versionCode:" + TTWORDS.getAppSetting().getVersionCode());
        Log.d("LoginPresenter", "REAL versionCode:" + TTWORDS.getVersionCode());
        if (TTWORDS.getAppSetting().getVersionCode() < TTWORDS.getVersionCode()) {
            DBTool.deleteDB();
            checkDataBase();
        }
    }

    /**
     * 验证用户名是邮箱还是手机号
     *
     * @param username 用户名
     * @return 返回种类检测结果。
     */
    private String checkUnameKind(String username) {
        String result;
        String epattern = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
        Pattern ep = Pattern.compile(epattern);//复杂匹配
        Matcher em = ep.matcher(username);

        String tpattern = "1\\d{10}";
        Pattern tp = Pattern.compile(tpattern);//复杂匹配
        Matcher tm = tp.matcher(username);
        if (em.matches()) {
            result = "EMAIL";
        } else if (tm.matches()) {
            result = "TEL";
        } else {
            result = "TEL";
        }
        return result;
    }
}
